import validHtml from 'ngtemplate!html!../../../tpls/dialog/valid.dialog.html';

class CpEditController {
    constructor($rootScope, $scope, $cookieStore, $timeout, $state, ngDialog, dialogService, CpService, getCpDetail, iRunner, getDeviceList){

        var vm = this;

        vm.$rootScope    = $rootScope;
        vm.$cookieStore  = $cookieStore;
        vm.$timeout      = $timeout;
        vm.$state        = $state;
        vm.ngDialog      = ngDialog;
        vm.dialogService = dialogService;
        vm.CpService     = CpService;
        vm.getCpDetail   = getCpDetail;
        vm.iRunner       = iRunner;
        vm.getDeviceList = getDeviceList;

        // 表单数据初始化
        vm.cp = {
            cp_name: '',
            cp_index: '',
            cp_type: ''
        }

        console.log(vm.getCpDetail.data);
        // 获取CP点详情
        if (vm.getCpDetail.code==0) {
            var Detail = vm.getCpDetail.data;
            vm.cp.cp_name     = Detail.cp_name;
            vm.cp.cp_index    = Detail.cp_index;
            // 是否是视频点
            vm.isLiveVideo    = Detail.is_camera_point == 'yes' ? true : false;
            // 是否是计时点
            vm.isTimingPoint    = Detail.is_timing_point == 'yes' ? true : false;
            // 计时点id
            vm.isLiveVideoId = Detail.camera_id == 0 ? '' : Detail.camera_id;
        }

        //已绑定设备列表
        vm.bindEquipmentList = vm.getCpDetail.data.device;
        console.log(vm.getCpDetail.data.device);

        //待绑定设备列表
        vm.list = [];
        for(var key in vm.getDeviceList.data){
           vm.list.push(vm.getDeviceList.data[key]);//往数组中放属性
        }
        vm.equipmentList = vm.list;

        //像下拉框中添加已绑定设备
        angular.forEach(vm.bindEquipmentList, function (element, index) {
            $("#select_id").append("<option selected value='" + element.mid + "'>" + element.title + "</option>");
        });

        //向下拉框中添加待绑定设备
        angular.forEach(vm.equipmentList, function (element, index) {
            $("#select_id").append("<option value='" + element.mid + "'>" + element.title + "</option>");
        });


        var config = {
            '.chosen-select'           : {},
            '.chosen-select-deselect'  : {allow_single_deselect:true},
            '.chosen-select-no-single' : {disable_search_threshold:10},
            '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}
        }

        for (var selector in config) {
            $(selector).chosen(config[selector]);
        }

        // 获取123赛事id
        vm.CpService.getTrelated(vm.$cookieStore.get('access_token'), vm.$state.params.race_id)
        .then( data => {
            console.log("data");
            console.log(data);
            if (data.code == 0) {
                vm.camera_id = data.data.related_id;
            }
            // 调用失败, 提示用户
            (data.code!=0&&data.code!=-1001)&&vm.dialogService.error(data.message);
            // 登录信息已过期, 请重新登录
            data.code==-1001&&vm.dialogService.error(data.message, true);
        }, error => console.log('error'));

        //删除摄像点
        vm.delete_camera_id = function(id) {
            //调用张榕接口获取视频赛事id
            var raceid = vm.camera_id;
            //调用123接口（视频）--5.删除摄像点信息
            var baseurl = "http://www.123yd.cn/xingjiansport/V2/XiaoAi/removeCameraPoint?raceid=" + raceid + "&cameraid=" + id;
            $.get(baseurl, {}, function (data2) {
                if (data2.errorcode != 0) {
                    vm.dialogService.error(data2.errormsg);
                } else {
                    console.log('删除成功--' + raceid + '--' + id);
                    console.log(data2);
                }
            }, 'json');
        }

        // 创建摄像点
        vm.create_camera_id = function(id) {
            //调用123接口（视频）--3.创建摄像点
            //http://www.123yd.cn/xingjiansport/V2/XiaoAi/createCameraPoint?raceid=31&cameraid=15&longitude=121.363839&latitude=31.161295
            var raceid = vm.camera_id;
            var baseurl = "http://www.123yd.cn/xingjiansport/V2/XiaoAi/createCameraPoint?raceid=" + raceid + "&cameraid=" + id + "&longitude=0&latitude=0";
            $.get(baseurl, {}, function (data2) {
                if (data2.errorcode != 0) {
                    vm.dialogService.error(data2.errormsg);
                } else {
                    console.log('创建成功--' + raceid + '--' + id);
                    console.log(data2);
                }
            }, 'json');
        }

    }


    // 表单提交
    submitForm(isValid) {
        var vm = this;
        // 验证失败, 提示用户
        if (!isValid) {
            if (!vm.cp.cp_name) {
                $.blink(angular.element(document.getElementsByName('cpName')), 5, 100)
            }
        }

        // 验证通过
        if (isValid) {

            var mid = '';
            angular.forEach(vm.bindEquipment, function (element, index) {
                mid += element + ',';
            });

            $(".search-choice span").each(function(index, element) {
                angular.forEach(vm.bindEquipmentList, function (element2, index2) {
                    if (element2.title == element.innerHTML && mid.indexOf(element2.mid) == -1) {
                        mid += element2.mid + ',';
                    }
                });
            });

            // 拼接POST数据格式
            var params = {
                cp_index: vm.cp.cp_index,
                cp_name: vm.cp.cp_name,
                mid: mid.substring(0, mid.length - 1),
                is_camera_point: vm.isLiveVideo ? 'yes' : 'no',
                is_timing_point: vm.isTimingPoint ? 'yes' : 'no',
                camera_id: vm.isLiveVideoId
            }

            // 计时点列表
            vm.CpService.postCpUpdate(params, vm.$cookieStore.get('access_token'), vm.$state.params.cp_id)
            .then( data => {

                // 成功调用
                data.code==0&&vm.dialogService.success('更新成功', 'dashboard.race.detail');

                if (data.code == 0) {
                    //摄像点改为非摄像点的场合
                    if ((vm.isLiveVideo != (vm.getCpDetail.data.is_camera_point == 'yes' ? true : false)) && !vm.isLiveVideo) {
                        console.log('摄像点改为非摄像点的场合');
                        // 循环删除摄像点
                        angular.forEach(vm.bindEquipmentList, function(data, index, array) {
                            if (data.type == "camera") {
                                // 创建摄像点
                                vm.delete_camera_id(data.name);
                            }
                        });

                    } else if ((vm.isLiveVideo != (vm.getCpDetail.data.is_camera_point == 'yes' ? true : false)) && vm.isLiveVideo) {
                        // 非摄像点改为摄像点的场合
                        console.log('非摄像点改为摄像点的场合');
                        // 循环创建摄像点
                        // 新添加的设备
                        if (vm.bindEquipment) {
                            angular.forEach(vm.getDeviceList.data, function(data, index, array) {
                                angular.forEach(vm.bindEquipment, function(data2, index2, array2) {
                                    // console.log(data2);
                                    if (data2 == data.mid) {
                                        // 创建摄像点
                                        vm.create_camera_id(data.name);
                                    }
                                });
                            });
                        }

                        // 原本绑定的设备
                        console.log(vm.bindEquipmentList);
                        angular.forEach(vm.bindEquipmentList, function(data, index, array) {
                            console.log(data);
                            if (data.type == "camera") {
                                // 创建摄像点
                                vm.create_camera_id(data.name);
                            }
                        });
                        
                    } else if ((vm.isLiveVideo == (vm.getCpDetail.data.is_camera_point == 'yes' ? true : false)) && vm.isLiveVideo) {
                        // （摄像点---》摄像点） 的场合
                        console.log('（摄像点---》摄像点）');
                        // 新添加的设备
                        if (vm.bindEquipment) {
                            angular.forEach(vm.getDeviceList.data, function(data, index, array) {
                                angular.forEach(vm.bindEquipment, function(data2, index2, array2) {
                                    // console.log(data2);
                                    if (data2 == data.mid && data.type == "camera") {
                                        // 创建摄像点
                                        vm.create_camera_id(data.name);
                                    }
                                });
                            });
                        }


                        // 原有的
                        console.log(vm.bindEquipmentList);
                        // 现行所有
                        console.log(params.mid.split(","));
                        //原来有而现在没有的进行删除
                        angular.forEach(vm.bindEquipmentList, function(data, index, array) {
                            var checkFlag = false;
                            angular.forEach(params.mid.split(","), function(data2, index2, array2) {
                                if (data2 == data.mid) {
                                    checkFlag = true;
                                }
                            });

                            if (!checkFlag) {
                                // 删除摄像点
                                vm.delete_camera_id(data.name);
                            }
                        });

                    } else {
                        console.log('未改变');
                    }
                }

                // 调用失败, 提示用户
                (data.code!=0&&data.code!=-1001)&&vm.dialogService.error(data.message);

                // 登录信息已过期, 请重新登录
                data.code==-1001&&vm.dialogService.error(data.message, true);
                
                console.log(data)
            }, error => console.log('error'));
        }

        return false;
    }


    // 删除计时点
    deleteItems(cp_id) {
        var vm = this;
        // 模态框显示文本
        vm.$rootScope.common = {
            text : '是否删计时点信息'
        }


        vm.ngDialog.open({
            template: validHtml,
            className: 'ngdialog-theme-default ngdialog-alert',
            scope: vm.$rootScope
        });

        // 提交表单
        vm.$rootScope.submitDelForm = (isValid) => {

            // 验证失败, 提示用户
            if (!isValid) {
                vm.dialogService.error();
            }

            // 验证通过
            if (isValid) {

                // 关闭模态框
                vm.ngDialog.close();

                vm.CpService.postCpDel({cp_id: cp_id}, vm.$cookieStore.get('access_token'), vm.$state.params.race_id)
                .then( data => {
                    
                    // 成功调用
                    data.code==0&&vm.dialogService.success('计时点删除成功', 'dashboard.race.detail');

                    if (data.code==0) {
                        // 循环删除摄像点
                        angular.forEach(vm.bindEquipmentList, function(data, index, array) {
                            if (data.type == "camera") {
                                // 创建摄像点
                                vm.delete_camera_id(data.name);
                            }
                        });
                    }
                    
                    // 调用失败, 提示用户
                    (data.code!=0&&data.code!=-1001)&&vm.dialogService.error(data.message);

                    // 登录信息已过期, 请重新登录
                    data.code==-1001&&vm.dialogService.error(data.message, true);

                    console.log(data)
                }, error => console.log('error'));
            }

            return false;
        }  
    }
}

CpEditController.$inject = ['$rootScope', '$scope', '$cookieStore', '$timeout', '$state', 'ngDialog', 'dialogService', 'CpService', 'getCpDetail', 'iRunner', 'getDeviceList']; 

export default CpEditController;